package com.glasgowcompsoc.musicplayer.ui;

import java.util.List;

import com.glasgowcompsoc.musicplayer.player.Song;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Shader.TileMode;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

public class AlbumArtAdapter extends BaseAdapter {
	private Context mContext;

	private List<Song> songs;

	public AlbumArtAdapter(Context c, List<Song> songs) {
		this.mContext = c;
		this.songs = songs;
	}

	public int getCount() {
		return songs.size();
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	/*
	 * Demonstrates the "view holder" pattern. This pattern allows a "view holder" (group of widgets which have already
	 * been allocated memory) to be re-used in a list, avoiding costly allocation of memory and garbage collection.
	 * 
	 * When an item of the list is no longer visible (i.e. the user scrolled down the list), the view holder is
	 * recycled, allowing existing objects in memory to be reused. When this was introduced at Google IO a couple of
	 * years ago, they reckoned it improved speed in complex lists by 60+%. Pretty cool, huh?
	 */
	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView v = (ImageView) convertView;

		if (v == null) {
			v = new ImageView(mContext) {
				private Paint shinePaint = new Paint(Paint.ANTI_ALIAS_FLAG); // Smooth edges!
				private Path shinePath = new Path();

				protected void dispatchDraw(Canvas canvas) {
					// Create a path that forms the shine effect
					shinePath.moveTo(0, 0);
					shinePath.lineTo((int) (getWidth() * 0.65), 0);
					shinePath.lineTo((int) (getWidth() * 0.15), getHeight());
					shinePath.lineTo(0, getHeight());
					shinePath.close();

					// Draw the items inside the view (i.e. draw the album art)
					super.dispatchDraw(canvas);

					// Add the shine onto of the album art
					shinePaint.setShader(new LinearGradient(0, 0, 0, getHeight(), 0x22ffffff, 0x00ffffff,
							TileMode.CLAMP));
					canvas.drawPath(shinePath, shinePaint);
				}
			};
			
			v.setLayoutParams(new Gallery.LayoutParams(350, 350));
			v.setScaleType(ImageView.ScaleType.CENTER_CROP);
		}
		
		/* Create an AsyncTask to get the cover art for this song. */
		FetchAlbumArtTask task = new FetchAlbumArtTask(mContext, v);
		task.execute(songs.get(position));

		return v;
	}
}